﻿using System;
using System.Collections.Generic;

namespace TLang.Parsers
{
    using Ast;

    public class PreParser
    {
        private readonly String _file;
        private readonly Lexer _lexer;

        public PreParser(string text, string file)
        {
            this._file = file;
            this._lexer = new Lexer(text, file);
        }

        /**
         * Get next node from token stream
         */
        private Node NextNode()
        {
            return _lexer.NextNode(0);
        }

        /**
         * Parse file into a Node
         *
         * @return a Tuple containing the file's parse tree
         */
        public Node Parse()
        {
            List<Node> elements = new List<Node>();
            elements.Add(GenName(Constants.SeqKeyword));      // synthetic block keyword

            Node s = NextNode();
            Node first = s;
            Node last = null;
            for (; s != null; last = s, s = NextNode())
            {
                elements.Add(s);
            }

            return new TupleNode(
                    elements: elements,
                    open: GenName(Constants.ParenBegin),
                    close: GenName(Constants.ParenEnd),
                    file: _file,
                    start: first?.Start ?? 0,
                    end: last?.End ?? 0,
                    line: 0,
                    col: 0
            );
        }

        /**
         * Generate a name without location info
         */
        private static NameNode GenName(String id)
        {
            return new NameNode(id, null, 0, 0, 0, 0);
        }
    }
}
